from contextlib import contextmanager
from flask import Flask,current_app
from config import configs
from flask_sqlalchemy import SQLAlchemy as _SQLAlchemy
import logging
from redis import StrictRedis
from logging.handlers import RotatingFileHandler
from redis import StrictRedis
from flask_session import Session
from flask_wtf import CSRFProtect
from flask_wtf.csrf import generate_csrf


class SQLAlchemy(_SQLAlchemy):
    @contextmanager
    def auto_commit(self):
        try:
            yield
            self.session.commit()
        except Exception as e:
            self.session.rollback()


db = SQLAlchemy()
redis_store = None

def setup_log(config_name):
    logging.basicConfig(level=configs[config_name].LOG_LEVEL)
    file_logo_handler = RotatingFileHandler('logs/log',maxBytes=1024*1024*100,backupCount=10)
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    file_logo_handler.setFormatter(formatter)
    logging.getLogger().addHandler(file_logo_handler)


def create_app(config_name):
    setup_log(config_name)
    app = Flask(__name__)
    app.config.from_object(configs[config_name])
    global redis_store
    redis_store = StrictRedis(host=configs[config_name].REDIS_HOST,
                              port=configs[config_name].REDIS_PORT,
                              decode_responses=True)
    register_plugin(app)
    @app.after_request
    def after_requset(response):
        csrf_token = generate_csrf()
        response.set_cookie('csrf_token',csrf_token)
        return response

    register_bp(app)

    return app


def register_bp(app):
    from app.modules.index import index_bp
    app.register_blueprint(index_bp)
    from app.modules.trade import trade_bp
    app.register_blueprint(trade_bp)

def register_plugin(app):
    db.init_app(app)
    db.create_all(app=app)
    Session(app)
    CSRFProtect(app)

